/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import dao.DAOCuaHangProduct;
import dao.DAOListCuaHang;
import dao.DAOPersonnel;
import dao.DAOProduct;
import dao.DAOStore;
import dao.DAOStoreProduct;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import plugin.DatePicker;
import pojo.CuahangProduct;
import pojo.ListCuahang;
import pojo.Personnel;
import pojo.PersonnelDetail;
import pojo.Product;
import pojo.Store;
import pojo.StoreProduct;
import pojo.StoreProductId;

/**
 *
 * @author QTuan
 */
public class XuatHangKho extends javax.swing.JPanel {

    /**
     * Creates new form XuatHangKho
     */
    private DefaultTableModel model = new DefaultTableModel();
    private PersonnelDetail account= null;
    private String taikhoan = "";
    private List<CuahangProduct> dsCuaHangSanPham = new ArrayList<CuahangProduct>();
    public XuatHangKho(PersonnelDetail account,String taikhoan) {
        initComponents();
        this.account = account;
        this.taikhoan = taikhoan;
        DAOListCuaHang daoListcuahang = new DAOListCuaHang();
        List<ListCuahang> dsCuaHang = daoListcuahang.getAll();
        for(int i=0;i<dsCuaHang.size();i++)
        {
            this.jComboBox1.addItem(dsCuaHang.get(i).getName());
        }
        model.addColumn("Id");
        model.addColumn("Tên sản phẩm");
        model.addColumn("Số lượng tồn");
        model.addColumn("Giá");
        model.addColumn("Số lương tối đa");
        model.addColumn("Số lượng tối thiểu");
        model.addColumn("Số lượng xuất");
        this.jTable1.setModel(model);
        this.jSpinner1.setValue(1);
        this.jComboBox1.addActionListener(new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        
    }
});
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jSpinner1 = new javax.swing.JSpinner();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        jButton1.setText("Lưu phiếu");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Xuất hàng cho cửa hàng");

        jLabel2.setText("Ngày xuất hàng");

        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTextField1MouseReleased(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jLabel3.setText("Cửa hàng");

        jLabel4.setText("Ngày tạo");

        jTextField2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField2MouseClicked(evt);
            }
        });
        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField2KeyPressed(evt);
            }
        });

        jLabel5.setText("Danh sách hàng xuất kho");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel6.setText("Nhập id hoặc quét mã sản phẩm");

        jButton2.setText("Enter");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        jLabel7.setText("Nhân viên giao hàng");

        jButton3.setText("Kiểm tra");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Xóa sản phẩm");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(50, 50, 50)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jComboBox1, 0, 204, Short.MAX_VALUE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField4))
                                .addGap(39, 39, 39)
                                .addComponent(jButton3)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(39, 39, 39)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(19, 19, 19)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(48, 48, 48)
                                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 604, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton3))
                        .addGap(14, 14, 14)
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2)
                            .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MouseReleased
        this.jTextField1.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField1MouseReleased

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        this.jTextField1.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField1KeyPressed

    private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField2MouseClicked
        this.jTextField2.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField2MouseClicked

    private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyPressed
        this.jTextField2.setText(new DatePicker(this).setPickedDate());
    }//GEN-LAST:event_jTextField2KeyPressed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String strid = this.jTextField3.getText();
        if(TryParseInt(strid)!=null)
        {
            Integer id = Integer.parseInt(strid);
             boolean flag = false;
            for(int i=0;i<model.getRowCount();i++)
            {
                int temp = (Integer)model.getValueAt(i, 0);
                if((Integer)model.getValueAt(i, 0) == id)
                {
                    flag = true;
                    break;
                }
            }
            if(flag)
            {
                JOptionPane.showMessageDialog(null, "Sản phẩm đã có trong danh sách nhập hàng","Lỗi trùng",JOptionPane.ERROR_MESSAGE);
            }else
            {
                DAOProduct daoProduct = new DAOProduct();
                Product product = daoProduct.getProductById(id);
                if(product==null)
                {
                    JOptionPane.showMessageDialog(null, "Sản phẩm bạn tìm không tồn tại xin nhập lại hoặc tạo mới sản phẩm","Lỗi không tìm thấy",JOptionPane.ERROR_MESSAGE);
                }else
                {
                    int soluongxuat = (Integer)this.jSpinner1.getValue();
                    String tenCuaHang = (String)this.jComboBox1.getSelectedItem();
                    DAOListCuaHang daocuahang = new DAOListCuaHang();
                    ListCuahang cuahang = daocuahang.getCuaHangByName(tenCuaHang);
                    DAOCuaHangProduct daocuahangproduct = new DAOCuaHangProduct();
                    CuahangProduct ProductCuaHang = daocuahangproduct.getCuaHangProductById(cuahang.getId(), product.getId());
                    if(ProductCuaHang==null)
                    {
                        JOptionPane.showMessageDialog(null, "Cửa hàng không nhập sản phẩm này.","Không tìm thấy sản phẩm",JOptionPane.ERROR_MESSAGE);
                    }else
                    {
                        if(ProductCuaHang.getCount()< ProductCuaHang.getToithieuL())
                        {
                            JOptionPane.showMessageDialog(null, "Mặt hàng này cửa hàng đã tồn kho quá nhiều.","Lỗi quy định số lượng tối thiểu xuất(Quy định 3)",JOptionPane.ERROR_MESSAGE);
                        }else
                        {
                            if(product.getProCount()-soluongxuat < product.getProCountN())
                            {
                                JOptionPane.showMessageDialog(null, "Cần giữ lại số lượng hàng tối thiểu trong kho(hàng trong kho đã hết).","Lỗi hết hàng",JOptionPane.ERROR_MESSAGE);
                            }else
                            {
                                if(ProductCuaHang.getCount()+soluongxuat > ProductCuaHang.getToidaK())
                                {
                                    JOptionPane.showMessageDialog(null, "Số lượng hàng tại cửa hàng đã đủ số lương tối đa.","Lỗi hàng bị quá tải",JOptionPane.ERROR_MESSAGE);
                                }else
                                {
                                    model.addRow(new Object[]{product.getId(),product.getProName(),product.getProCount(),product.getProPrice(),product.getProCountM(),product.getProCountN(),soluongxuat});
                                    this.dsCuaHangSanPham.add(ProductCuaHang);
                                }
                            }
                        }
                    }
                    
                    
                }
            }
        }else
        {
            JOptionPane.showMessageDialog(null, "Bạn phải nhập id là số","Lỗi id",JOptionPane.ERROR_MESSAGE);
        }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(model.getRowCount()==0)
        {
            JOptionPane.showMessageDialog(null, "Không thể lưu phiếu nếu không có sản phẩm nào","Lỗi thiếu sản phẩm xuất",JOptionPane.ERROR_MESSAGE);
        }else
        {
            if(this.jTextField1.getText().equals(""))
            {
                JOptionPane.showMessageDialog(null, "Hãy chọn ngày xuất hàng để tiếp tục!","Thiếu ngày xuất",JOptionPane.WARNING_MESSAGE);
            }else
            {
                Store billStore = new Store();
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                Date dateXuat = null;
                Date dateTao = null;
                try {
 
                    dateXuat = formatter.parse(this.jTextField1.getText());
                    if(this.jTextField2.getText().equals(""))
                    {
                        dateTao = new Date();
                    }else
                    {
                        dateTao = formatter.parse(this.jTextField2.getText());
                    }
                    
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DAOPersonnel daoPersonnel = new DAOPersonnel();
                Personnel accountGiao = daoPersonnel.getAccount(this.jTextField4.getText());
                if(accountGiao==null)
                {
                    JOptionPane.showMessageDialog(null, "Không có nhân viên này thuộc công ty vui lòng nhập lại","Lỗi không tìm thấy nhân viên",JOptionPane.ERROR_MESSAGE);
                }else
                {
                    
                    billStore.setDtimeBill(dateXuat);
                    billStore.setDtimeCreate(dateTao);
                    billStore.setDtimeUpdate(dateXuat);
                    billStore.setIsBlock(0);
                    billStore.setPerAccount(this.taikhoan);
                    billStore.setPerAccountDelivery(accountGiao.getPerAccount());
                    //get cua hang hien tai
                   String tenCuaHang = (String)this.jComboBox1.getSelectedItem();
                    DAOListCuaHang daocuahang = new DAOListCuaHang();
                    ListCuahang cuahang = daocuahang.getCuaHangByName(tenCuaHang);
                    //DAOCuaHangProduct daocuahangproduct = new DAOCuaHangProduct();
                    billStore.setCuaHang(cuahang.getName());
                    billStore.setDiachi(cuahang.getDiachi());
                    DAOProduct daoProduct = new DAOProduct();
                   List<Product> productList = new ArrayList<Product>();
                   List<Integer> soluonghangthem = new ArrayList<Integer>();
                   for(int i=0;i<model.getRowCount();i++)
                    {
                        Product temp = daoProduct.getProductById((Integer)model.getValueAt(i, 0));
                        temp.setProCount(temp.getProCount()- (Integer)model.getValueAt(i, 6));
                        
                        
                        //int idmodel = (Integer)model.getValueAt(i, 0);
                        productList.add(temp);
                        soluonghangthem.add((Integer)model.getValueAt(i, 6));
                    }
                   
                    
                    DAOStore daoStore = new DAOStore();
                    daoStore.setStore(billStore,productList,soluonghangthem,this.dsCuaHangSanPham);
                    JOptionPane.showMessageDialog(null, "Lưu hóa đơn thanh công","Lưu hóa đơn thanh công",JOptionPane.INFORMATION_MESSAGE);
                }
                
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        DAOPersonnel daoPersonnel = new DAOPersonnel();
        Personnel accountGiao = daoPersonnel.getAccount(this.jTextField4.getText());
        if(accountGiao==null)
        {
            JOptionPane.showMessageDialog(null, "Không có nhân viên này thuộc công ty vui lòng nhập lại","Lỗi không tìm thấy nhân viên",JOptionPane.ERROR_MESSAGE);
        }else
        {
            JOptionPane.showMessageDialog(null, "Có thể dùng nhân viên này","Có thể dùng nhân viên này",JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        int[] select = this.jTable1.getSelectedRows();
        for(int i=0;i<select.length;i++)
        {
            model.removeRow(select[i]);
        }
    }//GEN-LAST:event_jButton4ActionPerformed
    public static Integer TryParseInt(String someText) {
        try {
            return Integer.parseInt(someText);
        } catch (NumberFormatException ex) {
        return null;
        }
    }
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
}
